<script setup lang="ts">
import { ref, watch, h } from 'vue';
import { NButton, NPopconfirm, NSpace, NTag } from 'naive-ui';
import { fetchProjectMembers, addProjectMember, updateProjectMember, deleteProjectMember } from '@/service/api';
import { useBoolean } from '@sa/hooks';
import { useFormRules, useNaiveForm } from '@/hooks/common/form';

defineOptions({
  name: 'ProjectMemberDrawer'
});

interface Props {
  projectId?: number;
}

const props = defineProps<Props>();

const visible = defineModel<boolean>('visible', { required: true });

const { bool: loading, setTrue: startLoading, setFalse: endLoading } = useBoolean();
const { bool: modalVisible, setTrue: openModal, setFalse: closeModal } = useBoolean();
const { formRef, validate } = useNaiveForm();
const { defaultRequiredRule } = useFormRules();

const members = ref<Api.Dataplatform.ProjectMember[]>([]);
const operateType = ref<'add' | 'edit'>('add');

const model = ref<Api.Dataplatform.ProjectMemberEdit>({
  projectId: 0,
  userId: 0,
  userName: '',
  role: 'VIEWER'
});

const roleOptions = [
  { label: '负责人', value: 'OWNER' },
  { label: '管理员', value: 'ADMIN' },
  { label: '开发者', value: 'DEVELOPER' },
  { label: '查看者', value: 'VIEWER' }
];

const rules = {
  userId: defaultRequiredRule,
  role: defaultRequiredRule
};

const columns = [
  { key: 'userName', title: '用户名称', width: 150 },
  { key: 'userId', title: '用户ID', width: 120 },
  {
    key: 'role',
    title: '角色',
    width: 120,
    render: (row: Api.Dataplatform.ProjectMember) => {
      const roleMap: Record<string, { type: any; label: string }> = {
        OWNER: { type: 'error', label: '负责人' },
        ADMIN: { type: 'warning', label: '管理员' },
        DEVELOPER: { type: 'info', label: '开发者' },
        VIEWER: { type: 'default', label: '查看者' }
      };
      const role = roleMap[row.role] || roleMap.VIEWER;
      return h(NTag, { type: role.type }, { default: () => role.label });
    }
  },
  { key: 'joinTime', title: '加入时间', width: 180 },
  {
    key: 'actions',
    title: '操作',
    width: 150,
    fixed: 'right' as const,
    render: (row: Api.Dataplatform.ProjectMember) => {
      return h(NSpace, {}, {
        default: () => [
          h(NButton, { size: 'small', onClick: () => handleEdit(row) }, { default: () => '编辑' }),
          row.role !== 'OWNER' && h(NPopconfirm, { onPositiveClick: () => handleDelete(row.id!) }, {
            default: () => '确定删除该成员吗？',
            trigger: () => h(NButton, { size: 'small', type: 'error' }, { default: () => '删除' })
          })
        ].filter(Boolean)
      });
    }
  }
];

async function getMembers() {
  if (!props.projectId) return;
  
  startLoading();
  const { data, error } = await fetchProjectMembers(props.projectId);
  if (!error) {
    members.value = data || [];
  }
  endLoading();
}

function handleAdd() {
  operateType.value = 'add';
  model.value = {
    projectId: props.projectId!,
    userId: 0,
    userName: '',
    role: 'VIEWER'
  };
  openModal();
}

function handleEdit(row: Api.Dataplatform.ProjectMember) {
  operateType.value = 'edit';
  Object.assign(model.value, row);
  openModal();
}

async function handleDelete(id: number) {
  const { error } = await deleteProjectMember(id);
  if (!error) {
    window.$message?.success('删除成功');
    getMembers();
  }
}

const submitLoading = ref(false);

async function handleSubmit() {
  await validate();
  submitLoading.value = true;

  const api = operateType.value === 'add' ? addProjectMember : updateProjectMember;
  const { error } = await api(model.value);

  submitLoading.value = false;

  if (!error) {
    window.$message?.success(operateType.value === 'add' ? '添加成功' : '更新成功');
    closeModal();
    getMembers();
  }
}

watch(visible, val => {
  if (val) {
    getMembers();
  }
});
</script>

<template>
  <NDrawer v-model:show="visible" title="项目成员管理" display-directive="show" :width="800">
    <NDrawerContent title="项目成员管理" closable>
      <div class="h-full flex-col">
        <div class="pb-12px">
          <NButton type="primary" size="small" @click="handleAdd">
            <icon-ic-round-plus class="mr-4px text-20px" />
            添加成员
          </NButton>
        </div>

        <NDataTable
          :columns="columns"
          :data="members"
          :loading="loading"
          :scroll-x="700"
          class="flex-1-hidden"
        />
      </div>
    </NDrawerContent>

    <NModal v-model:show="modalVisible" :title="operateType === 'add' ? '添加成员' : '编辑成员'" preset="card" class="w-600px">
      <NForm ref="formRef" :model="model" :rules="rules" label-placement="left" :label-width="100">
        <NFormItem label="用户ID" path="userId">
          <NInputNumber v-model:value="model.userId" placeholder="请输入用户ID" class="w-full" :disabled="operateType === 'edit'" />
        </NFormItem>
        <NFormItem label="用户名称" path="userName">
          <NInput v-model:value="model.userName" placeholder="请输入用户名称" />
        </NFormItem>
        <NFormItem label="角色" path="role">
          <NSelect v-model:value="model.role" :options="roleOptions" placeholder="请选择角色" />
        </NFormItem>
      </NForm>

      <template #footer>
        <NSpace justify="end">
          <NButton @click="closeModal">取消</NButton>
          <NButton type="primary" :loading="submitLoading" @click="handleSubmit">提交</NButton>
        </NSpace>
      </template>
    </NModal>
  </NDrawer>
</template>
